"""
MyQuant期货API调用示例 (gm.api实现)
完整覆盖：基础数据、行情数据、合约数据、资金费率、持仓数据
注意：需要先安装gm库并设置token：pip install gm
"""

# 导入gm库
from gm.api import *
import pandas as pd
import numpy as np


# 登录gm账号（使用您的真实token）
def init():
    # 使用真实token替换此处字符串
    set_token('0dc802db1a918f7c064237478e69b83a024028e7')


class MyQuantAPI:
    def __init__(self):
        init()

    def get_symbol_info(self, symbol):
        """获取合约基础信息"""
        instrument = get_instrumentinfos(symbols=symbol)
        return pd.DataFrame(instrument)

    def get_trading_days(self, exchange='SHFE', start_date='2023-01-01', end_date='2023-12-31'):
        """获取交易日历"""
        days = get_trading_dates(exchange=exchange, start_date=start_date, end_date=end_date)
        return pd.DataFrame({'trade_date': days})

    def get_daily_data(self, symbol, start_date, end_date):
        """获取日线行情"""
        data = history(symbol=symbol, frequency='1d',
                       start_time=start_date, end_time=end_date,
                       fields='open,high,low,close,volume,open_interest,pre_close',
                       adjust=ADJUST_PREV)
        return pd.DataFrame(data)

    def get_minute_data(self, symbol, date, freq='1m'):
        """获取分钟行情"""
        data = history(symbol=symbol, frequency=freq,
                       start_time=date + ' 09:00:00',
                       end_time=date + ' 15:00:00',
                       fields='open,high,low,close,volume,open_interest',
                       adjust=ADJUST_PREV)
        return pd.DataFrame(data)

    def get_tick_data(self, symbol, date, freq='tick'):
        """获取历史tick数据"""
        data = history(symbol=symbol, frequency=freq,
                       start_time=date + ' 09:00:00',
                       end_time=date + ' 15:00:00',
                       # fields='bob,ask_bp1,ask_bp2,bid_bp1,bid_bp2')
                       fields='symbol,open,high,low,price,cum_volume,'
                              'cum_amount,cum_position,trade_type,last_volume,last_amount,'
                              'created_at,quotes', adjust=ADJUST_NONE, adjust_end_time='2020-12-31', df=True)
        return pd.DataFrame(data)

    def get_funding_rate(self, symbol):
        """获取资金费率"""
        # 期货的资金费率通常是固定的0，此处展示接口调用方式
        return pd.DataFrame({
            'symbol': [symbol],
            'funding_rate': [0.0],
            'effective_date': [pd.Timestamp.now().strftime('%Y-%m-%d')]
        })

    def get_open_interest(self, symbol, start_date, end_date):
        """获取持仓量数据"""
        # 日线数据已包含持仓量，专为持仓量设计的接口
        # data = get_futures_oi(symbol=symbol,
        #                       start_date=start_date,
        #                       end_date=end_date,
        #                       fields='symbol,volume,oi')
        # return pd.DataFrame(data)
        pass


# 测试所有API
def test_all_apis():
    api = MyQuantAPI()
    symbol = 'SHFE.rb2509'
    symbol = 'SHFE.RB'

    print("\n=== 标的基本信息 ===")
    infos = get_symbol_infos(sec_type1=1040, symbols= symbol)
    print(infos)


    print("\n=== 合约基础信息 ===")
    info = api.get_symbol_info(symbol)
    print(info)

    print("\n=== 交易日历 ===")
    # 如果是某个合约，就是这个合约的交易开始日到结束日
    calendar = api.get_trading_days()
    print(calendar.head())

    print("\n=== 日线数据 ===")
    daily = api.get_daily_data(symbol, '2023-07-01', '2023-07-10')
    print(daily.head())

    print("\n=== 分钟数据 ===")
    minutes = api.get_minute_data(symbol, '2025-07-15', '15m')
    print(minutes.head())

    print("\n=== Tick数据 ===")
    ticks = api.get_tick_data(symbol, '2025-07-15')
    print(ticks.head())

    print("\n=== 资金费率 ===")
    funding = api.get_funding_rate(symbol)
    print(funding)

    print("\n=== 持仓量数据 ===")
    # oi = api.get_open_interest(symbol, '2023-07-01', '2023-07-10')
    # print(oi.head())
    contracts = fut_get_continuous_contracts(csymbol=symbol, start_date="2025-09-09", end_date="2025-09-09")
    print(contracts)

    # 设定您关心的交易日和品种
    target_date = '2025-09-09'  # 您指定的日期
    symbol_prefix = 'SHFE.rb'  # 您指定的品种代码前缀
    # 通常，获取某个交易日所有期货合约的基本信息
    # 注意：这里的 '1040' 通常代表期货这种资产类型，具体值请查阅平台文档
    all_contracts_on_date = get_symbols(sec_type1=1040, trade_date=target_date, df=True)
    # 从所有合约中筛选出代码以 'SHFE.rb' 开头的合约，即螺纹钢合约
    rb_contracts = all_contracts_on_date[all_contracts_on_date['symbol'].str.startswith(symbol_prefix)]
    # 展示筛选后的合约信息，例如合约代码、名称等
    print(rb_contracts[['symbol', 'sec_name', 'listed_date', 'delisted_date']])

if __name__ == '__main__':
    test_all_apis()
